using System;
using System.Collections.Generic;
using Yoozoo.Framework.Core;

namespace Yoozoo.Mars.Got.Timer
{
    public class CountDownTool : Singleton<CountDownTool>
    {
        private readonly Dictionary<CountDownType, int> _typeToTimerIndex = new Dictionary<CountDownType, int>();
        private readonly Dictionary<int, CountDownType> _timerIndexToType = new Dictionary<int, CountDownType>();
        private readonly Dictionary<int, Action> _onStopDic = new Dictionary<int, Action>();

        public void Add(CountDownType countDownType, long countDownTime, Action<long> onRefresh, Action onStop)
        {
            Remove(countDownType);
            var mTimerIndex = TimeTool.Instance.Countdown(countDownTime, onRefresh, StopCountdown);
            if (onStop != null)
            {
                if (_onStopDic.ContainsKey(mTimerIndex))
                {
                    _onStopDic[mTimerIndex] = onStop;
                }
                else
                {
                    _onStopDic.Add(mTimerIndex, onStop);
                }
            }
            _typeToTimerIndex.Add(countDownType, mTimerIndex);
            _timerIndexToType.Add(mTimerIndex, countDownType);
        }

        public void Remove(CountDownType countDownType)
        {
            if (!_typeToTimerIndex.ContainsKey(countDownType))
            {
                return;
            }
            var timerIndex = _typeToTimerIndex[countDownType];
            if (timerIndex == -1)
            {
                return;
            }

            Action onStop;
            if (_onStopDic.TryGetValue(timerIndex, out onStop))
            {
//                onStop();
                _onStopDic.Remove(timerIndex);
            }

            TimeTool.Instance.RemoveTimeEvent(timerIndex);
            _typeToTimerIndex.Remove(countDownType);
            _timerIndexToType.Remove(timerIndex);
        }

        private void StopCountdown(int timerIndex)
        {
            Action onStop;
            if (_onStopDic.TryGetValue(timerIndex, out onStop))
            {
                onStop();
                _onStopDic.Remove(timerIndex);
            }
            TimeTool.Instance.RemoveTimeEvent(timerIndex);
            _typeToTimerIndex.Remove(_timerIndexToType[timerIndex]);
            _timerIndexToType.Remove(timerIndex);
        }
    }
}

